<template>
  <div class="login">
    <van-nav-bar title="登录" fixed />
    <van-cell-group>
      <van-form @submit="onSubmit">
        <van-field
          required
          v-model="mobile"
          label="手机号"
          placeholder="请输入手机号"
          :rules="rules.mobile"
        />
        <van-field
          required
          v-model="code"
          type="code"
          label="验证码"
          placeholder="请输入验证码"
          :rules="rules.code"
        />
        <div style="margin: 16px;">
          <van-button
            round
            block
            type="info"
            native-type="submit"
            :loading="loading"
            >提交</van-button
          >
        </div>
      </van-form>
    </van-cell-group>
  </div>
</template>

<script>
import { Userlogin } from '@/api/user'
export default {
  name: 'login',
  data() {
    return {
      mobile: '13212312312',
      code: '246810',
      loading: false,
      rules: {
        mobile: [
          { required: true, message: '请填写手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
        ],
        code: [
          { required: true, message: '请填写验证码' },
          { pattern: /^\d{6}$/, message: '验证码格式不正确' }
        ]
      }
    }
  },
  methods: {
    async onSubmit() {
      this.loading = true
      try {
        const res = await Userlogin(this.mobile, this.code)
        console.log('登录', res)
        this.$toast.success('登录成功')
        this.$store.commit('user/setToken', res.data)
        this.$router.push('/')
      } catch (error) {
        this.$toast.fail('登陆失败')
      }
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
.login {
  padding-top: 50px;
}
</style>
